package com.qzxy.premiumhotelsystem.controller.oauth;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qzxy.premiumhotelsystem.common.constant.UserRoleConstant;
import com.qzxy.premiumhotelsystem.common.result.Result;
import com.qzxy.premiumhotelsystem.domain.entity.Admin;
import com.qzxy.premiumhotelsystem.service.AdminService;
import com.qzxy.premiumhotelsystem.utils.GiteeHttpClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author: iQNRen
 * @Description: gitee三方登录接口
 * @Date: 2024/9/21 22:28 周六
 * @Version: 1.0
 */
@Tag(name = "gitee三方登录接口")
@RestController
@RequestMapping(value = "/oauth")
public class GiteeController {

    /**
     * gitee授权中提供的 appid 和 appkey
     */
    @Value("${gitee.oauth.clientid}")
    public String CLIENTID;
    @Value("${gitee.oauth.clientsecret}")
    public String CLIENTSECRET;
    @Value("${gitee.oauth.callback}")
    public String URL;
    @Autowired
    private AdminService adminService;
    /**
     * 请求授权页面
     */
    @GetMapping()
    @Operation(summary = "auth")
    public Result qqAuth(HttpSession session) {
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1：获取Authorization Code
        String url = "https://gitee.com/oauth/authorize?response_type=code" +
                "&client_id=" + CLIENTID +
                "&redirect_uri=" + URLEncoder.encode(URL) +
                "&state=" + uuid +
                "&scope=user_info";
        //因为使用的是thymeleaf模板引擎，所以是无法解析一个网址的，只能重定向
        return Result.ok(url);
//        return Result.ok("redirect:" + url);
    }

    /**
     * 授权回调
     */
    @GetMapping(value = "/callback")
    @Operation(summary = "callback")
    public Result qqCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        // 得到Authorization Code
        String code = request.getParameter("code");
        // 我们放在地址中的状态码
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");

        // 验证信息我们发送的状态码
        if (null != uuid) {
            // 状态码不正确，直接返回登录页面
            if (!uuid.equals(state)) {
                Result.error("状态异常");
            }
        }

        // Step2：通过Authorization Code获取Access Token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&client_id=" + CLIENTID +
                "&client_secret=" + CLIENTSECRET +
                "&code=" + code +
                "&redirect_uri=" + URL;
        JsonNode accessTokenJson = GiteeHttpClient.getAccessToken(url);
        // Step3: 获取用户信息
        url = "https://gitee.com/api/v5/user?access_token=" + accessTokenJson.get("access_token").textValue();
        JsonNode jsonObject = GiteeHttpClient.getUserInfo(url);
        /**
         * 获取到用户信息之后，就该写你自己的业务逻辑了
         */

//        ObjectMapper mapper = new ObjectMapper();
//        JsonNode rootNode = mapper.readTree(JsonNode);
//
//        // 提取单个字段的值
//        String id = rootNode.get("id").asText();
        System.out.println(jsonObject);
        String id = jsonObject.get("id").asText();
        System.out.println(id);
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("giteeID", id);
        Admin one = adminService.getOne(wrapper);
        System.out.println(one);
        if (one != null) {
            StpUtil.login(one.getUsername(), new SaLoginModel()
                    .setExtra("role", UserRoleConstant.ADMIN));
            response.sendRedirect("http://localhost:8080/#/manage/login?who="+one.getUsername());
            return Result.ok("登录成功,请返回！");
        } else {
            response.sendRedirect("http://localhost:8080/#/manage/login?err=error");
            return Result.error("没有用户");
        }
    }
    @PostMapping("who/{name}")
    @Operation(summary = "查看谁登录")
    public Result who(@PathVariable String name){
        if(Objects.equals(name,StpUtil.getLoginId())){
            return Result.ok(StpUtil.getTokenInfo().tokenValue);
        }else{
            return Result.error("用户请登录");
        }
    }
}
